package com.mindata.blockchain.socket.handler.server.vote;

import com.mindata.blockchain.ApplicationContextProvider;
import com.mindata.blockchain.common.Commonvalue;
import com.mindata.blockchain.core.manager.DbBlockManager;
import com.mindata.blockchain.socket.DGL.msg.DGLVoteMsg;
import com.mindata.blockchain.socket.base.AbstractBlockHandler;
import com.mindata.blockchain.socket.body.votebody.DGLVoteBody;
import com.mindata.blockchain.socket.common.queue.base.MsgQueueManager;
import com.mindata.blockchain.socket.packet.BlockPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

public class DGLVoteHandler extends AbstractBlockHandler<DGLVoteBody> {
    private Logger logger = LoggerFactory.getLogger(DGLVoteHandler.class);
    Commonvalue commonvalue = ApplicationContextProvider.getBean(Commonvalue.class);
    DbBlockManager dbBlockManager = ApplicationContextProvider.getBean(DbBlockManager.class);

    @Override
    public Class<DGLVoteBody> bodyClass() {
        return DGLVoteBody.class;
    }

    @Override
    public Object handler(BlockPacket packet, DGLVoteBody bsBody, ChannelContext channelContext) throws Exception {
        // 处理DGL投票信息
        DGLVoteMsg voteMsg = bsBody.getVoteMsg();
        int concensusindex = (dbBlockManager.getLastBlockNumber() + 1) % commonvalue.getGroupsize();
        if (concensusindex != commonvalue.getNodeIndex()) {
            return null;
        }
//        logger.error("收到来自于<{}><DGL投票>消息，投票信息为[{}]", voteMsg.getAppId(), voteMsg);
        ApplicationContextProvider.getBean(MsgQueueManager.class).pushMsg(voteMsg);
        return null;
    }
}
